# from main import generate_bach_data
from msilib.schema import Component
from bson import ObjectId
from datetime import datetime, timedelta
import json
from faker import Faker
from textwrap import indent
from tqdm import tqdm
from pymongo.errors import BulkWriteError
from pymongo import UpdateOne, MongoClient

# if __name__ == "__main__":
#     fake = Faker()
#     OID_COUNT = 3
#     OPEN_ID_COUNT = 5
#     oids = [ObjectId() for _ in range(OID_COUNT)] #oids: 包含了随机生成指定数量且为ObjectId类型的oid
#     open_ids = [fake.uuid4() for _ in range(OPEN_ID_COUNT)] #open_ids: 包含了随机生成指定数量uuid作为open_id
#     start_datetime = datetime(2023, 12, 1)
#     end_datetime = datetime(2023, 12, 13)
#     result_list = generate_bach_data(start_datetime,end_datetime, 15, oids, open_ids,fake)
#     list_a = []
#     for i in result_list:
#         i['atime'] = i['atime'].isoformat()
#         i['oid'] = str(i['oid'])
#         i['open_id'] = str(i['open_id'])
#         list_a.append(i)
#     print(json.dumps(list_a, indent=4))


#################################################################################################################################

# d1 = {
#     'zs':[1, 2, 3],
#     'ls':[4, 5, 6],
#     'ww':[7, 8, 9],
#     'xl':[10, 11, 12],
# }
# d2 = {
#     'zs':4,
#     'ls':7,
#     'ww':10,
#     'xl':13,
# }
# d3 = {
#     'zs':5,
#     'ls':8,
#     'ww':11,
#     'xl':14,
# }
# # 将其他字典中按照指定追加到指定字典中
# # 效率更高（原地操作）
# # for key in d1.keys():
# #     d1[key].append(d2[key])
# #     d1[key].append(d3[key])
# # 可读性更强（更简洁，创造一个新的字典）
# # d1 = {k: v + [d2[k], d3[k]] for k, v in d1.items()}
# data = {
#     'zs': [2, 3],
#     'ls': [1, 6],
#     'ww': [7, 5],
#     'xl': [10, 11],
# }

# # 根据每个键值对中的值列表的第二个元素进行排序
# sorted_data_items = sorted(data.items(), key=lambda item: item[1][1], reverse=True)

# # 将排序后的键值对列表转换回字典
# sorted_data = {key: value for key, value in sorted_data_items}

# # print(json.dumps(sorted_data, indent=4))
# print(sorted_data)
#################################################################################################################################
# def to_chinese(num):
#     numbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
#     tens = ['', '十', '二十', '三十', '四十', '五十', '六十', '七十', '八十', '九十']
#     if num < 10:
#         return numbers[num]
#     elif num < 20:
#         return '十' + (numbers[num % 10] if num % 10 != 0 else '')
#     else:
#         return tens[num // 10] + (numbers[num % 10] if num % 10 != 0 else '')

# def chinese_numbers(start, count=1):
#     for i in range(start, start + count):
#         yield to_chinese(i)

# # 使用示例：根据数字生成指定中文数字
# for name in chinese_numbers(99):
#     print(name)
#################################################################################################################################


# MONGO_URL = 'mongodb://localhost:27017/'
# mongo_client = MongoClient(MONGO_URL)
# user_widget_collection = mongo_client['novapps_server']['ios_widget_analysis_user_widget']
# component_list_collection = mongo_client['novapps_server']['ios_widget_component_library_module_list']
# # 生成数据


# def generate_batch_data(size):
#     data_list = []
#     for _ in range(size):
#         post_data = {
#             '_id': ObjectId(),
#             'name': _,
#             'tag': _,
#             'atime': datetime.now(),
#             'version': 0,
#             'thumb_url': None,
#             'pag_url': None,
#             'bg_url': None,
#             'widget_class_type': 0,
#             'widget_type': 0,
#             'widget_index': 0,
#             'is_island': False,
#             'other_data': {},
#             'is_lock': False,
#         }
#         data_list.append(post_data)
#     return data_list
# # 插入数据


# def insert_data(data_list):
#     user_widget_collection.insert_many(data_list)
#     print(f'共插入{len(data_list)}条数据')


# def insert_batch_data(data_list, mongo_collection, batch_size=10000):
#     '''
#     将一个大的列表分批插入到数据库
#     output: 插入的数据量大小
#     '''
#     print('开始插入数据：')
#     total = len(data_list)
#     progress_bar = tqdm(desc='插入数据', unit='条')
#     for i in range(0, total, batch_size):
#         batch = data_list[i:i+batch_size]
#         try:
#             mongo_collection.bulk_write([
#                 UpdateOne(
#                     {'_id': document['_id']},
#                     {'$setOnInsert': document},    # 数据不存在时插入数据，数据存在则什么也不做
#                     upsert=True
#                 )for document in batch
#             ])
#             progress_bar.update(len(batch))  # 更新进度条
#             print(
#                 f'Inserted batch {i//batch_size + 1}/{(total // batch_size) + 1}')
#         except BulkWriteError as bwe:
#             print(bwe.details)  # 打印详细的错误信息
#             break  # 发生错误时跳出循环
#         except Exception as e:
#             print(f'General Error inserting batch {i//batch_size + 1}: {e}')
#             break  # 发生错误时跳出循环
#     progress_bar.close()  # 关闭进度条
#     print('完成插入')
#     return total


# if __name__ == "__main__":
#     component_list_collection.drop()
#     data_list = generate_batch_data(10000)
#     insert_batch_data(data_list=data_list, mongo_collection=component_list_collection, batch_size=1000)

###########################################################################################################################
# import sys
# from bson import BSON

# # 伪造一条记录以进行测试
# post_data = {
#     'atime': '2021-02-25T00:00:00Z',  # ISO日期长度为24字节
#     'oid': '507f1f77bcf86cd799439011',  # ObjectId 的字符串表示形式
#     'view_count': 123,                  # 整数值
#     'view_count_user': 456,
#     'click_count': 789,
#     'click_count_user': 1011,
#     'complete_set_count': 1213,
#     'complete_set_count_user': 1415,
#     'click_rate': 0.1,                  # 浮点数也大约占用8个字节
#     'complete_set_rate': 0.2,
# }

# # 将记录编码为BSON格式并获取其大小
# bson_encoded = BSON.encode(post_data)
# size_in_bytes = len(bson_encoded)

# print(f"Approximate size of a single document: {size_in_bytes} bytes")

# # 总计可用的最大BSON文档大小（16MB）
# max_bson_size = 16 * 1024 * 1024

# # 计算大约可以存储多少条这样的记录
# approx_num_records = max_bson_size // size_in_bytes

# print(f"Approximate number of documents that can fit in 16MB BSON: {approx_num_records}")

###########################################################################################################################
# from datetime import datetime
# from dateutil.rrule import rrule, DAILY

# # start_date = datetime(2023, 12, 5)

# start_date = datetime.now() - timedelta(days=30) # 从昨天往前数第30天
# end_date = datetime.now()- timedelta(days=1) # 昨天
# def get_time(year: int, month: int, day: int):
#     # 构造查询时间
#     date_to_query = datetime(year=year, month=month, day=day)
#     start_of_day = datetime(date_to_query.year, date_to_query.month, date_to_query.day)
#     end_of_day = datetime(date_to_query.year, date_to_query.month, date_to_query.day, 23, 59, 59)
#     return start_of_day, end_of_day

# for dt in rrule(DAILY, dtstart=start_date, until=end_date):
#     d = get_time(dt.year, dt.month, dt.day)
#     print(d[0],d[1])  # 或者执行其他操作

###########################################################################################################################

# dt = datetime(2023, 12, 5).strftime('%Y-%m-%d')
# print(dt)

###########################################################################################################################
import redis
# 默认连接本地 Redis 实例
redis_client = redis.Redis(host='localhost', port=6379, db=0)
# 发送PING命令测试连接
response = redis_client.ping()

print(f"Response from Redis: {response}")

